<script>
export default {
  name: "ShoppingCart",
  data() {
    return {
      a: 0,
      carId:0,
      isBatchMode: false,
      // multipleSelection: [],
      addressInfo: [],
      // 用户登陆的id
      userId: '',
      userAddress: '',
      // 购物模态框的显隐
      dialogGouWu: false,
      tableData4: [],

      orderInfo: {
        goodsId: 0,
        picture: '',
        goodsMoney: 0,
        address: '',
        userId: 0,
        goodsName: '',
        buyCount: 0,
        allMoney: 0,
        goodsList: [],
      },

    }
  },
  computed: {
    // 计算数量
    totalQuantity() {
      let total = 0;
      this.tableData4.forEach(item => {
        total += Number(item.buyCount);
      });
      return total;
    },
    // 计算总金额
    totalPrice() {
      let total = 0;
      this.tableData4.forEach(item => {
        total += Number(item.allMoney);
      });
      return total;
    },
    // 计算选中数量
    totalQuantityOn() {
      let total = 0;
      this.orderInfo.goodsList.forEach(item => {
        total += Number(item.buyCount);
      });
      return total;
    },
    // 计算选中金额
    totalPriceOn() {
      let total = 0;
      this.orderInfo.goodsList.forEach(item => {
        total += Number(item.allMoney);
      });
      return total;
    },
  },
  methods: {
    // 购买所选商品
    gouMaiSuoXuanShangPin() {
      this.a = 2;
      console.log("购买所选商品")
      // 商品数据在 this.orderInfo.goodsList中,this.orderInfo.goodsList是一个数组，数组中是每个商品的信息对象，有一些商品id（this.orderInfo.goodsList.goodsId）重复，但是购买数量（this.orderInfo.goodsList.buyCount）不重复，我想让其合并，怎么做？
      console.info(this.orderInfo.goodsList)

      if (this.orderInfo.goodsList.length === 0) {
        this.$message.warning("请选择要购买的商品")
        return
      }
      this.dialogGouWu = true

      // 合并相同的 goodsId
      const mergedGoods = {};
      this.orderInfo.goodsList.forEach(item => {
        if (mergedGoods[item.goodsId]) {
          mergedGoods[item.goodsId].buyCount += item.buyCount;
          mergedGoods[item.goodsId].allMoney += item.allMoney;
        } else {
          mergedGoods[item.goodsId] = {...item};
        }
      });

      // 将合并后的结果转换回数组
      this.orderInfo.goodsList = Object.values(mergedGoods);

      console.log("转换后")
      console.info(this.orderInfo.goodsList)

      // 填充用户id与用户地址
      this.orderInfo.userId = this.userId
      this.orderInfo.address = this.userAddress
      // 检查库存
      // this.inJianChaKuCun();
    },
    // 取消批量购买
    toggleBatchMode() {
      this.isBatchMode = !this.isBatchMode;
      if (!this.isBatchMode) {
        this.orderInfo.goodsList = []; // 取消批量购买时清空已选商品列表
      }
    },
    querySearch(queryString, cb) {
      cb(this.addressInfo);
    },
    // 获取跟据用户id获取用户的地址
    loadAll() {
      this.$http.post('user/findAddressByUserId', {userId: this.userId})
          .then(res => {
            this.addressInfo = res.data
          })
    },
    // 填充选择的地址
    handleSelect(item) {
      this.orderInfo.address = item.address
    },

    //移除
    removeFromCart(row) {
      // 跟据订单id移除
      this.$http.post("/car/deleteCarByCarId", {carId: row.carId})
          .then(res => {
            if (res.data.msg === 1) {
              this.findCarByUid();
              this.$message.success("移除成功")
            } else {
              this.$message.error("移除失败")
            }
          })
    },
    // 查询购物车的初始数据
    findCarByUid() {
      this.$http.post("/car/listAllById", {userId: this.userId})
          .then(res => {
            console.log("购物车初始数据")
            console.info(res.data)
            res.data.forEach(item => {
              let i1 = Number(item.goodsMoney.split("元")[0]);
              item.goodsMoney = i1
              item.allMoney = i1 * Number(item.buyCount)

              item.goodsPicture = "http://localhost:2011/picture/" + item.goodsPicture + '.jpg'
            })
            this.tableData4 = res.data;
          })
    },
    // 单商品结算
    jieSuan(row) {
      this.a = 1
      console.log("结算按钮（单商品结算 row信息）")
      console.info(row)
      this.carId = row.carId
      // 点击结算 回显部分数据 并且传入商品id 计算总价
      this.orderInfo.goodsList = [row];

      this.orderInfo.userId = this.userId
      this.orderInfo.goodsName = row.goodsName
      this.orderInfo.goodsMoney = row.goodsMoney
      this.orderInfo.buyCount = row.buyCount
      this.orderInfo.address = this.userAddress
      this.orderInfo.goodsId = row.goodsId
      this.orderInfo.allMoney = Number(this.orderInfo.buyCount) * Number(this.orderInfo.goodsMoney)
      this.addressInfo = this.loadAll();
      this.dialogGouWu = true
    },
    // 购买所有 按钮 先检查库存 => 清除和提示库存不足的商品，询问是否购买库存足够的商品
    piLiangGouMai() {
      // 批量购买的按钮展示
      this.isBatchMode = true
      console.log("批量购买按钮")
      console.info(this.orderInfo)

      // this.dialogGouWu = true
    },
    // 计算总价
    handleChange() {
      this.orderInfo.allMoney = Number(this.orderInfo.buyCount) * Number(this.orderInfo.goodsMoney)
    },
    // 提交 添加订单
    tiJiaoTianJiaDingDan() {
      let total = 0;
      this.orderInfo.goodsList.forEach(item => {
        total += Number(item.allMoney);
      });
      this.orderInfo.allMoney = total;
      console.log("最后的提交")
      console.info(this.orderInfo)
      this.$http.post('/order/addOrderByUserId', this.orderInfo, {headers: {'Content-Type': 'application/json'}})
          .then(res => {
            if (res.data.msg === 1) {
              this.$message.success("购买成功,请在10分钟内付款")
              this.findCarByUid();
            } else {
              this.$message.error("购买失败")
            }
            console.log(res)
          })
    },

    // 检查库存
    inJianChaKuCun() {
      console.log("检查库存中的订单信息")
      console.info(this.orderInfo)
      let i = [];
      this.orderInfo.goodsList.forEach(item => i.push(item.goodsId))
      let getGoodsKuCun = this.$http.post('goods/findGoodsCountByGoodsId', {goodsIdList: i}, {headers: {'Content-Type': 'application/json'}});
      getGoodsKuCun.then(res => {
        // 跟据商品id查到的商品库存
        console.log("跟据商品id查到的商品库存")
        console.info(res.data)
        if (res.data.length === 1) {// 单商品结算
          if (res.data[0].count >= this.orderInfo.buyCount) {
            this.$message.success("库存足够")
            // this.$message.success("选择支付方式");
            this.tiJiaoTianJiaDingDan();
          } else {
            this.$message.warning("库存不足，购买失败");
          }
        } else { // 多商品结算
          let buZu = [];
          // 判断选中的商品是否有库存 res.data => 商品id与库存 对象。 this.orderInfo.goodsList包含商品的购买数量与商品id及其他信息
          // 需要跟据商品库存（res.data.count）和用户购买数量（this.orderInfo.goodsList.buyCount）的关系，判断商品是否足够（他们之间商品id相等）
          res.data.forEach(item => {
            // 找到 goodsList 中与当前 item.goodsId 相同的商品
            const correspondingItem = this.orderInfo.goodsList.find(goods => goods.goodsId === item.goodsId);
            // 如果找到了对应的商品并且库存不足
            if (correspondingItem && item.count < correspondingItem.buyCount) buZu.push(item.goodsId);
          })
          console.log("不足的商品")
          console.info(buZu)
          console.log("现商品")
          console.info(this.orderInfo.goodsList)

          if (buZu.length > 0) {
            // 跟据商品不足的id 查找下面数组的内容，并删除
            this.orderInfo.goodsList = this.orderInfo.goodsList.filter(item => !buZu.includes(item.goodsId));
            this.orderInfo.allMoney = this.totalPriceOn;
            console.log("移除后的订单信息")
            console.info(this.orderInfo)
            this.$message.warning("以下商品库存不足，已从购物车中移除: " + buZu.join(', '));
          }
          // 询问是否继续购买库存足够的商品，有取消和确定 点击取消可以终止购买，点击购买再继续购买逻辑
          if (this.orderInfo.goodsList.length > 0 && buZu.length > 0) {
            const continuePurchase = confirm("部分商品库存不足，已从购物车中移除。是否继续购买剩余商品?" + `剩余商品总价${this.totalPriceOn}`);
            if (continuePurchase) this.tiJiaoTianJiaDingDan(); else this.$message.info("您已取消购买");
          } else if (this.orderInfo.goodsList.length >= 0 && buZu.length === 0) {
            this.tiJiaoTianJiaDingDan()
            this.$message.success("所有商品库存满足")
          } else if (this.orderInfo.goodsList.length === 0) {
            this.$message.warning("所有商品库存不足，无法继续购买。");
          }
        }

      })

    },
    // 购物模态框的提交
    dialogGouWuTiJiao() {
      console.log("订单信息")
      console.info(this.orderInfo)
      // 检查商品是否足够
      this.inJianChaKuCun();
      this.dialogGouWu = false
    },
    handleSelectionChange(val) {
      // this.multipleSelection = val;
      this.orderInfo.goodsList = val;
    },
    // 模态框保存按钮 保存用户修改的地址和数量
    baoCun() {
      // 获取 商品 数量 id(车)
      this.$http.post('/car/updateCountByGoodsId', {goodsId: this.carId, buyCount: this.orderInfo.buyCount})
          .then(res => {
            console.log("保存")
            console.info(res)
            if (res.data.msg === 1) {
              this.$message.success("保存成功")
              this.findCarByUid();
            } else {
              this.$message.error("保存失败")
            }

          })
      this.dialogGouWu = false;
    }

  },
  created() {
    let item = sessionStorage.getItem('user_info');
    if (item != null) {
      this.userId = JSON.parse(item).id;
      this.userAddress = JSON.parse(item).address;
    }

    this.findCarByUid();
  },

}
</script>

<template>
  <div>
    <!-- 购买物品模态框开始 -->
    <el-dialog title="确认信息" :visible.sync="dialogGouWu" width="35%" append-to-body>


      <el-form ref="form" :model="orderInfo" label-width="80px">
        <div v-if="a===1">
          <el-form-item label="商品单价">
            <el-input v-model="orderInfo.goodsMoney" disabled class="dialog_input"/>
          </el-form-item>
          <el-form-item label="数量">
            <el-input-number v-model="orderInfo.buyCount" @change="handleChange" :min="0" :max="1000" label="商品数量"/>
          </el-form-item>
          <el-form-item label="总价钱">
            <el-input v-model="orderInfo.allMoney" disabled class="dialog_input"/>
          </el-form-item>
        </div>

        <el-form-item label="收货地址">

          <el-autocomplete popper-class="my-autocomplete" v-model="orderInfo.address" :fetch-suggestions="querySearch"
                           size="medium" placeholder="请选择或手动输入地址" @select="handleSelect">
            <i class="el-icon-edit el-input__icon" slot="suffix"/>
            <template slot-scope="{ item }">
              <span class="addr">{{ item.address }}</span>
            </template>
          </el-autocomplete>

        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="baoCun()">保存</el-button>
    <el-button type="primary" @click="dialogGouWuTiJiao()">提交订单</el-button>
  </span>
    </el-dialog>
    <!-- 购买物品模态框结束 -->
    共计：{{ totalQuantity }}个商品，{{ totalPrice }}元&nbsp;&nbsp;&nbsp;&nbsp;<br/><br/>
    <el-button v-if="!isBatchMode" type="warning" @click="piLiangGouMai()">批量购买</el-button>
    <el-button v-if="isBatchMode" type="info" @click="toggleBatchMode">取消批量购买</el-button>
    <el-button v-if="isBatchMode" type="primary" @click="gouMaiSuoXuanShangPin">购买所选商品</el-button>

    <span v-if="orderInfo.goodsList.length>0">已选中：{{ totalQuantityOn }}个商品，共计{{ totalPriceOn }}元</span>
    <el-table :data="tableData4" max-height="10000" show-checkbox @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" v-if="isBatchMode"/>
      <el-table-column label="商品图片" width="150">
        <template #default="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.goodsPicture" fit="cover"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="goodsName" label="商品名" width="120"/>
      <el-table-column prop="buyCount" label="购买数量" width="120"/>
      <el-table-column prop="goodsMoney" label="商品单价" width="120"/>
      <el-table-column prop="allMoney" label="商品总价" width="120"/>
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-button type="danger" @click="removeFromCart(scope.row)">移除</el-button>
          <el-button type="primary" @click="jieSuan(scope.row)">结算</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.dialog_input {
  width: 180px;
}

.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }

    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>